package com.gwthtml.samples.chatdemo.server;

import java.util.ArrayList;
import java.util.List;

import com.gwthtml.samples.chatdemo.client.ChatMessage;
import com.gwthtml.samples.chatdemo.client.ChatService;
import com.gwthtml.servlet.RemoteHtmlServiceServlet;

public class ChatServiceImpl extends RemoteHtmlServiceServlet implements ChatService {

	private static List<ChatMessage> messages = new ArrayList<ChatMessage>();
	
	private static int seqNum = 1;
	
	public ChatMessage[] sendMessage(ChatMessage toSend, int latestSeq) {
		synchronized (messages) {
			if (messages.size() >= 10) {
				messages.remove(0);
			}
			if (toSend != null) {
				if (toSend.getMessage() != null && toSend.getNick() != null) {
					if (toSend.getMessage().trim().length() != 0
							&& toSend.getNick().trim().length() != 0) {
						messages.add(toSend);
						toSend.setSequenceNum(seqNum++);
					}
				}
			}
			int latestSeqNumInList = 0;
			if (messages.size() > 0) {
				latestSeqNumInList = messages.get(messages.size() -1).getSequenceNum();
			}
			if (latestSeq < 0) latestSeq = 0;
			if (latestSeq < latestSeqNumInList) {
				int missingSeqs = latestSeqNumInList - latestSeq;
				List<ChatMessage> subl = messages.subList(Math.max(0, messages.size() - missingSeqs), messages.size());
				ChatMessage[] result = new ChatMessage[subl.size()];
				int i = 0;
				for (ChatMessage m : subl) {
					result[i++] = m;
				}
				return result;
			}
		}
		return null;
	}
}
